﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Simple Variance Sample</title>
<style type="text/css">
</style>
</head>

<body>
<p>The <strong>SimpleVariance</strong> sample program shows C# 4.0 support for 
covariance and contravariance when using generic types in delegates and 
interfaces. In C# 3.0 generic types were invariant. As a result, this sample compiles fine in C# 4.0, while it 
does not compile in previous versions of C#.</p>

<p>There program first declares two simple classes and two delegates:</p>

<pre class="code"><span style="color: blue">class</span>  <span style="color: #2b91af">Animal</span> { }
<span style="color: blue">class</span> <span style="color: #2b91af">Cat</span> : <span style="color: #2b91af">Animal</span> { }

<span style="color: blue">delegate </span>T <span style="color: #2b91af">Func1</span>&lt;<span style="color: blue">out </span>T&gt;();
<span style="color: blue">delegate void </span><span style="color: #2b91af">Action1</span>&lt;<span style="color: blue">in </span>T&gt;(T a);</pre>
<p>It then implements the delegates and uses the classes:</p>
<pre class="code"><span style="color: #2b91af">Func1</span>&lt;<span style="color: #2b91af">Cat</span>&gt; cat = () =&gt; <span style="color: blue">new </span><span style="color: #2b91af">Cat</span>();
<span style="color: #2b91af">Action1</span>&lt;<span style="color: #2b91af">Animal</span>&gt; act1 = (ani) =&gt; { <span style="color: #2b91af">Console</span>.WriteLine(ani); };</pre>

<p>It then makes the assignments that requires covariant and contravariant support:</P>

<pre class="code"><span style="color: #2b91af">Func1</span>&lt;<span style="color: #2b91af">Animal</span>&gt; animal = cat;
<span style="color: #2b91af">Action1</span>&lt;<span style="color: #2b91af">Cat</span>&gt; cat1 = act1;</pre>

<p>It is this latter set of assignments that work in C# 4.0 but not in previous versions of C#. The first 
assignment illustrates coveriance, and the second contravariance.</p>
<p>The new contextual keywords <strong>out</strong> and <strong>in</strong> 
allow you to specify whether a generic type is going to be passed into a 
delegate or interface method, or returned from a delegate or interface method.</p>

</body>

</html>
